
<template>
  <div class="box">
    <h2>登录页面</h2>
    <el-form :model="ruleForm"
             status-icon
             :rules="rules"
             ref="ruleForm"
             label-width="100px"
             class="demo-ruleForm">
      <el-form-item label="手机号"
                    prop="phone">
        <el-input type="number"
                  v-model="ruleForm.phone"
                  autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码"
                    prop="password">
        <el-input type="password"
                  v-model="ruleForm.password"
                  autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// 对密码加密
import md5 from 'md5'
import { ElMessage } from 'element-plus';
import { getData } from '../../api/api'
export default {
  data () {
    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      }
      else {
        callback()
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        phone: '',
        password: '',
      },
      rules: {
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
      }
    };
  },
  methods: {
    // 发送
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 校验通过
          let res = getData({
            phone: this.ruleForm.phone,
            password: md5(this.ruleForm.password)
          })
            .then((res) => {
              // 登陆成功
              localStorage.setItem('token', res.token)
              localStorage.setItem('phone', this.ruleForm.phone)
              ElMessage.success('登陆成功')
              this.$router.push('/')
              console.log(md5(this.ruleForm.password));
            }).catch(err => {
              ElMessage.error('用户名或密码错误')
            })
        }
        // 校验失败
        else {
          ElMessage.error('请输入用户名和密码')
        }
      });
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>
.box {
  width: 50%;
  height: 200px;
  margin: 100px auto;
}
h2 {
  margin-bottom: 20px;
}
</style>